#include <iostream>
#include <modbus.h>
#include <errno.h>
#include <iomanip>  // for std::setprecision
#include <csignal>
#include <string>
#include "ModbusDevice.hpp"

bool is_running = true;

// Ctrl+C 信号处理函数
void signalHandler(int signum) {
    if (signum == SIGINT) {
        std::cout << "\n[INFO] 捕获到 Ctrl+C (SIGINT)，准备退出..." << std::endl;
        is_running = false;
    }
}


int main() {
    signal(SIGINT,signalHandler);
    
    try{
        std::string device = "/dev/ttyS1";  // 串口设备路径，根据实际情况修改
        int baud = 4800;                    // 文档默认波特率为 4800
        char parity = 'N';                  // 无校验位
        int data_bits = 8;
        int stop_bits = 1;
        int slave_id = 1;                   // 默认从机地址为 1

        auto modbus_device = ModbusDevice(device, baud, parity, data_bits, stop_bits,slave_id);

        modbus_device.SetResponseTimeout(1,0); // 设置超时时间为1.0s

        // 连接 Modbus 设备
        if (!modbus_device.ModbusConnect()) {
            std::cerr << "Connection failed: " << modbus_strerror(errno) << std::endl;
            modbus_free(modbus_device.ctx_);
            return -1;
        }

        // 读取前两个寄存器（0x0000: 含水率, 0x0001: 温度）
        uint16_t regs[2] = {0};
        while(is_running){
            int rc = modbus_read_registers(modbus_device.ctx_, 0x0000, 2, regs);
            if (!modbus_device.ModbusReadRegisters(0x0000,2,regs)) {
                std::cerr << "Read failed: " << modbus_strerror(errno) << std::endl;
                modbus_close(modbus_device.ctx_);
                modbus_free(modbus_device.ctx_);
                return -1;
            }

            // 解码寄存器
            float moisture = regs[0] / 10.0f;            // 含水率（文档中放大10倍）
            float temperature = (int16_t)regs[1] / 10.0f; // 温度（带符号值）

            std::cout << std::fixed << std::setprecision(1);
            std::cout << "🌱 Soil Sensor Data:" << std::endl;
            std::cout << "Moisture: " << moisture << " %" << std::endl;
            std::cout << "Temperature: " << temperature << " °C" << std::endl;

            sleep(3);
        }
        

        // // 关闭连接
        // modbus_close(ctx);
        // modbus_free(ctx);
    }
    catch(const std::exception & e){
        std::cerr << "Modbus Device Error " << e.what() << std::endl;
    }

    

    return 0;
}
